using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;
using Random = UnityEngine.Random;
using TMPro;
using Utility;


public class LevelController : MonoBehaviour
{
    public static LevelController Instance;
    public float waveTimer;
    public GameObject _failPanel; //失败面板
    public GameObject _successPanel; //成功面板
    public List<EnemyBase> enemy_list; //所有敌人列表
    public Transform _map;
    
    public GameObject enemy1_prefab;  // 敌人1预制体
    public GameObject enemy2_prefab;  // 敌人2预制体
    public GameObject enemy3_prefab;  // 敌人3预制体
    public GameObject enemy4_prefab;  // 敌人4预制体
    public GameObject enemy5_prefab;  // 敌人5预制体
    public Transform enemyFather; 
    
    public GameObject redfork_prefab;  //红叉预制体
    public TextAsset levelTextAsset; //json 
    public List<LevelData> levelDatas = new List<LevelData>(); //所有关卡信息
    public LevelData currentLevelData; //当前关卡信息

    public Dictionary<string, GameObject> enemyPrefabDic = new Dictionary<string, GameObject>();
    
    // 敌人生成控制
    private int currentEnemyCount = 0;
    private int maxActiveEnemies = 20; // 同时活跃敌人的最大数量
    private Queue<WaveData> enemySpawnQueue = new Queue<WaveData>(); // 等待生成的敌人队列
    private bool isProcessingQueue = false;
    
    // 对象池引用
    private ObjectPool objectPool;

    private void Awake()
    {
        Instance = this;

        _failPanel = GameObject.Find("FailPanel");
        _successPanel = GameObject.Find("SuccessPanel");
        enemy1_prefab = Resources.Load<GameObject>("Prefabs/Enemy1");
        enemy2_prefab = Resources.Load<GameObject>("Prefabs/Enemy2");
        enemy3_prefab = Resources.Load<GameObject>("Prefabs/Enemy3");
        enemy4_prefab = Resources.Load<GameObject>("Prefabs/Enemy4");
        enemy5_prefab = Resources.Load<GameObject>("Prefabs/Enemy5");
        
        redfork_prefab = Resources.Load<GameObject>("Prefabs/RedFork");
        _map = GameObject.Find("Map").transform;
        
        levelTextAsset = Resources.Load<TextAsset>("Data/" + GameManager.Instance.currentDifficulty.levelName);
        levelDatas = JsonConvert.DeserializeObject<List<LevelData>>(levelTextAsset.text);

        enemyFather = GameObject.Find("Enemys").transform;
        
        enemyPrefabDic.Add("enemy1", enemy1_prefab);
        enemyPrefabDic.Add("enemy2", enemy2_prefab);
        enemyPrefabDic.Add("enemy3", enemy3_prefab);
        enemyPrefabDic.Add("enemy4", enemy4_prefab);
        enemyPrefabDic.Add("enemy5", enemy5_prefab);
        
        // 初始化对象池
        GameObject poolObj = new GameObject("ObjectPool");
        objectPool = poolObj.AddComponent<ObjectPool>();
        
        // 确保所有预制体都已加载
        if (enemy1_prefab != null && enemy2_prefab != null && enemy3_prefab != null && 
            enemy4_prefab != null && enemy5_prefab != null && redfork_prefab != null && 
            GameManager.Instance.enemyBullet_prefab != null && GameManager.Instance.moeny_prefab != null)
        {
            // 为每种对象创建池
            objectPool.pools = new List<ObjectPool.Pool>
            {
                new ObjectPool.Pool { tag = "enemy1", prefab = enemy1_prefab, size = 20 },
                new ObjectPool.Pool { tag = "enemy2", prefab = enemy2_prefab, size = 10 },
                new ObjectPool.Pool { tag = "enemy3", prefab = enemy3_prefab, size = 10 },
                new ObjectPool.Pool { tag = "enemy4", prefab = enemy4_prefab, size = 10 },
                new ObjectPool.Pool { tag = "enemy5", prefab = enemy5_prefab, size = 10 },
                new ObjectPool.Pool { tag = "redfork", prefab = redfork_prefab, size = 10 },
                new ObjectPool.Pool { tag = "enemyBullet", prefab = GameManager.Instance.enemyBullet_prefab, size = 30 },
                new ObjectPool.Pool { tag = "money", prefab = GameManager.Instance.moeny_prefab, size = 20 }
            };
            
            // 初始化对象池（手动调用以确保立即执行）
            objectPool.InitializePoolsManually();
        }
        else
        {
            Debug.LogError("一个或多个预制体未能加载！对象池初始化失败。");
        }
    }

    void Start()
    {
        // 1. 首先检查关卡数据
        Debug.Log($"当前波次: {GameManager.Instance.currentWave}, 关卡数据数量: {levelDatas.Count}");
        
        // 如果关卡数据不足，动态生成更多关卡
        if (GameManager.Instance.currentWave > levelDatas.Count && levelDatas.Count > 0)
        {
            // 使用最后一关作为模板
            LevelData templateLevel = levelDatas[levelDatas.Count - 1];
            
            // 计算难度系数
            float difficultyMultiplier = 1.0f + (GameManager.Instance.currentWave - levelDatas.Count) * 0.15f;
            
            // 创建新关卡
            currentLevelData = new LevelData();
            
            // 复制波次时间
            currentLevelData.waveTimer = templateLevel.waveTimer;
            
            // 复制敌人列表
            currentLevelData.enemys = new List<WaveData>();
            foreach (WaveData enemyWave in templateLevel.enemys)
            {
                WaveData newWave = new WaveData();
                newWave.enemyName = enemyWave.enemyName;
                newWave.timeAxis = enemyWave.timeAxis;
                
                // 随波次增加敌人数量
                newWave.count = Mathf.CeilToInt(enemyWave.count * difficultyMultiplier);
                
                // 增加精英敌人概率
                if (Random.value < 0.1f * difficultyMultiplier)
                {
                    newWave.elite = 1;
                }
                else
                {
                    newWave.elite = 0;
                }
                
                currentLevelData.enemys.Add(newWave);
            }
            
            Debug.Log($"自动生成第 {GameManager.Instance.currentWave} 关数据，难度系数: {difficultyMultiplier}");
        }
        else
        {
            // 使用原始关卡数据
            int index = Mathf.Min(GameManager.Instance.currentWave - 1, levelDatas.Count - 1);
            currentLevelData = levelDatas[index];
        }
        
        // 设置波次时间
        waveTimer = currentLevelData.waveTimer;
        
        // 生成敌人
        GenerateEnemy();
        
        // 生成武器
        GenerateWeapon();
    }

    private void GenerateWeapon()
    {
        Debug.Log("生成武器开始");

        int i = 0;
        foreach (WeaponData weaponData in GameManager.Instance.currentWeapons)
        {
            GameObject go = Resources.Load<GameObject>("Prefabs/" + weaponData.name);
            WeaponBase wb = Instantiate(go, Player.Instance.weaponsPos.GetChild(i)).GetComponent<WeaponBase>();
            wb.data = weaponData;
            
            i++;
        }
        
        
        
        Debug.Log("生成武器结束");
    }


    private void GenerateEnemy()
    {
        //清空等待队列
        enemySpawnQueue.Clear();
        
        //遍历所有波次信息
        foreach (WaveData waveData in currentLevelData.enemys)
        {
            //遍历敌人数量
            for (int i = 0; i < waveData.count; i++)
            {
                // 将敌人放入生成队列，而不是立即生成
                enemySpawnQueue.Enqueue(waveData);
            }
        }   
        
        // 开始处理敌人生成队列
        StartCoroutine(ProcessEnemyQueue());
    }
    
    // 处理敌人生成队列
    IEnumerator ProcessEnemyQueue()
    {
        isProcessingQueue = true;
        
        while (enemySpawnQueue.Count > 0)
        {
            // 如果当前敌人数量已达到上限，等待一小段时间再检查
            if (currentEnemyCount >= maxActiveEnemies)
            {
                yield return new WaitForSeconds(0.5f);
                continue;
            }
            
            // 从队列中取出一个敌人数据
            WaveData waveData = enemySpawnQueue.Dequeue();
            StartCoroutine(SpawnEnemy(waveData));
            
            // 短暂延迟，避免在同一帧生成太多敌人
            yield return new WaitForSeconds(0.1f);
        }
        
        isProcessingQueue = false;
    }

    IEnumerator SpawnEnemy(WaveData waveData)
    {
        yield return new WaitForSeconds(waveData.timeAxis);
        
        if (waveTimer > 0 && !Player.Instance.isDead)
        {
            var spawnPoint = GetRandomPosition(_map.GetComponent<SpriteRenderer>().bounds);
            
            // 使用对象池生成红叉预警，添加错误处理
            GameObject redfork = null;
            if (objectPool != null)
            {
                redfork = objectPool.SpawnFromPool("redfork", spawnPoint, Quaternion.identity);
            }
            
            if (redfork == null)
            {
                // 如果对象池失败，使用传统方式
                redfork = Instantiate(redfork_prefab, spawnPoint, Quaternion.identity);
            }
            
            yield return new WaitForSeconds(1);
            
            // 返回红叉到对象池或销毁
            if (redfork != null)
            {
                if (objectPool != null)
                {
                    objectPool.ReturnToPool("redfork", redfork);
                }
                else
                {
                    Destroy(redfork);
                }
            }

            if (waveTimer > 0 && !Player.Instance.isDead)
            {
                // 尝试使用对象池生成敌人
                GameObject enemyObj = null;
                if (objectPool != null)
                {
                    enemyObj = objectPool.SpawnFromPool(waveData.enemyName, spawnPoint, Quaternion.identity);
                }
                
                // 如果对象池失败，使用传统方式
                if (enemyObj == null)
                {
                    if (enemyPrefabDic.ContainsKey(waveData.enemyName))
                    {
                        enemyObj = Instantiate(enemyPrefabDic[waveData.enemyName], spawnPoint, Quaternion.identity);
                    }
                    else
                    {
                        Debug.LogError("找不到敌人预制体: " + waveData.enemyName);
                        yield break;
                    }
                }
                
                EnemyBase enemy = enemyObj.GetComponent<EnemyBase>();
                if (enemy == null)
                {
                    Debug.LogError("生成的敌人没有 EnemyBase 组件");
                    Destroy(enemyObj);
                    yield break;
                }
                
                enemy.transform.SetParent(enemyFather);

                foreach (EnemyData e in GameManager.Instance.enemyDatas)
                {
                    if (e.name == waveData.enemyName)
                    {
                        // 深拷贝敌人数据，避免共享同一个引用
                        enemy.enemyData = JsonUtility.FromJson<EnemyData>(JsonUtility.ToJson(e));

                        //判断是否为精英
                        if (waveData.elite == 1)
                        {
                            enemy.SetElite();
                        }
                        
                        break;
                    }
                }
                
                enemy_list.Add(enemy);
                currentEnemyCount++;
            }
        }
    }
    
    // 敌人死亡时调用，减少计数
    public void OnEnemyDeath(EnemyBase enemy)
    {
        if (enemy_list.Contains(enemy))
        {
            enemy_list.Remove(enemy);
            currentEnemyCount--;
            
            // 如果队列处理已停止但还有敌人在队列中，重新启动处理
            if (!isProcessingQueue && enemySpawnQueue.Count > 0)
            {
                StartCoroutine(ProcessEnemyQueue());
            }
        }
    }
    
    //获取随机位置
    private Vector3 GetRandomPosition(Bounds bounds)
    {
        float safeDistance = 3.5f; //安全距离
        
        float randomX = Random.Range(bounds.min.x + safeDistance, bounds.max.x - safeDistance);
        float randomY = Random.Range(bounds.min.y + safeDistance, bounds.max.y - safeDistance);
        float randomZ = 0f;
        return new Vector3(randomX, randomY, randomZ);

    }

    // Update is called once per frame
    void Update()
    {
        if (waveTimer > 0 )
        {
            waveTimer -= Time.deltaTime;

            if (waveTimer <= 0)
            {
                waveTimer = 0;

                if (GameManager.Instance.isEndlessMode || GameManager.Instance.currentWave < 5)
                {
                    NextWave();
                }
                else
                {
                    GoodGame();
                }
                
            }
        }

        GamePanel.Instance.RenewCountDown(waveTimer);

    }
    
    //进入下一关
    private void NextWave()
    {
        // 基础收获
        int baseHarvest = GameManager.Instance.propData.harvest;
        
        // 无尽模式额外奖励
        if (GameManager.Instance.isEndlessMode)
        {
            // 随着波次增加，提供额外金币奖励
            int bonusCoins = 0;
            if (GameManager.Instance.currentWave > 5)
            {
                bonusCoins = (GameManager.Instance.currentWave - 5) * 5; // 每5波额外5金币
            }
            
            // 添加额外收获
            GameManager.Instance.money += baseHarvest + bonusCoins;
            
            // 显示额外奖励提示（可选）
            if (bonusCoins > 0)
            {
                Debug.Log("无尽模式额外奖励: " + bonusCoins + " 金币");
            }
        }
        else
        {
            // 原始逻辑
            GameManager.Instance.money += baseHarvest;
        }
        
        SceneManager.LoadScene("04-Shop");  //跳转商店
        GameManager.Instance.currentWave += 1; //波次+1
    }

    //生成敌人
    
    //游戏胜利
    public void GoodGame()
    {
        _successPanel.GetComponent<CanvasGroup>().alpha = 1;
        
        // 为无尽模式添加波次显示
        if (GameManager.Instance.isEndlessMode)
        {
            // 找到成功面板中的文本并显示波次数
            Transform successText = _successPanel.transform.Find("Text");
            if (successText != null && successText.GetComponent<TMP_Text>() != null)
            {
                successText.GetComponent<TMP_Text>().text = "恭喜通关!\n你在无尽模式中达到了第 " + GameManager.Instance.currentWave + " 波!";
            }
        }
        
        StartCoroutine(GoMenu());
        
        //todo 所有敌人 消失
        for (int i = 0; i < enemy_list.Count; i++)
        {
            if (enemy_list[i])
            {
                enemy_list[i].Dead();
            }
          
        }

        // 解锁角色逻辑保持不变
        if (PlayerPrefs.GetInt("多面手") == 0)
        {
            Debug.Log("多面手解锁");
            PlayerPrefs.SetInt("多面手", 1);

            for (int i = 0; i < GameManager.Instance.roleDatas.Count; i++)
            {
                if (GameManager.Instance.roleDatas[i].name == "多面手")
                {
                    GameManager.Instance.roleDatas[i].unlock = 1;
                }
            }
        }
        
    }
    
    
    //todo 波次完成
    
    //游戏失败
    public void BadGame()
    {
        _failPanel.GetComponent<CanvasGroup>().alpha = 1;
        StartCoroutine(GoMenu());
        
        
        //todo 所有敌人 消失
        for (int i = 0; i < enemy_list.Count; i++)
        {
            if (enemy_list[i])
            {
                enemy_list[i].Dead();
            }
          
        }
        
    }
    
     IEnumerator GoMenu()
     {
         yield return new WaitForSeconds(3);
         SceneManager.LoadScene(0);
     }
}
